/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.Sl;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.*;
import com.jeeplus.modules.fee.util.Exportprofit;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 应收Controller
 * @author 李超辉
 * @version 2018-02-01
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/receivable")
public class ReceivableController extends BaseController {

	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private RecivedDetilService service;
	@Autowired
	private CostService costService;
	@Autowired
	private JsService jsService;
	@Autowired
	private JsDetilService jsDetilService;
	@Autowired
	private CopeService copeService;
	@Autowired
	private SlService slService;
	@Autowired
	private ProfitService profitService;
	
	@ModelAttribute
	public Receivable get(@RequestParam(required=false) String id) {
		Receivable entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = receivableService.get(id);
		}
		if (entity == null){
			entity = new Receivable();
		}
		return entity;
	}
	
	/**
	 * 应收列表页面
	 */
	@RequiresPermissions("fee:receivable:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/receivableList";
	}

	/**
	 * 应收报表页面
	 */
	@RequiresPermissions("fee:receivable:list")
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/fee/2/receivableList";
	}
	/**
	 * 应收报表页面
	 */
	@RequestMapping(value = "list2")
	public String list2() {
		return "modules/fee/1/receivableList";
	}
	
		/**
	 * 应收列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivable:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Receivable receivable, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			receivable.setProject(pro);
		}

		Page<Receivable> page = receivableService.findPage(new Page<Receivable>(request, response), receivable);
		return getBootstrapData(page);
	}
	/**
	 * 应收列表数据(报表)
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivable:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Receivable receivable, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			receivable.setProject(pro);
		}
          receivable.setStatus("2");
		Page<Receivable> page = receivableService.findPage(new Page<Receivable>(request, response), receivable);
		return getBootstrapData(page);
	}
	/**
	 * 应收报表查询
	 */

	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro,String c,String s,String kp,String jsd){
		Receivable r=new Receivable();
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			r.setProject(pro);
		}else{
			if(!UserUtils.getUseroffice().equals("总部")){
				r.setProject(UserUtils.getUseroffice());
			}
		}
		r.setMax(max);
		r.setMin(min);
		r.setShipmentNumbers(c);
		r.setStatus(s);
		r.setReceived(kp);
		r.setArrive(jsd);
		List<Receivable> list=receivableService.findList(r);
		double zl=0.0;
		double bhs=0.0;
		double hs=0.0;
		double ad=0.0;
		double zje=0.0;
		double wkp=0.0;
		String ids="";
		for(Receivable re:list){
			zl+=Double.parseDouble(re.getWeight());
			bhs+=Double.parseDouble(re.getSurplus());
			hs+=Double.parseDouble(re.getHs());
			ad+=re.getAd();
			zje+=Double.parseDouble(re.getFreight());
			ids+=re.getId()+",";
			if(!re.getReceived().equals("1")){
				wkp+=Double.parseDouble(re.getFreight());
			}
		}
		NumberFormat nf = NumberFormat.getInstance();
		r.setWeight(nf.format(zl).replaceAll(",",""));
		r.setSurplus(nf.format(bhs).replaceAll(",",""));
		r.setHs(nf.format(hs).replaceAll(",",""));
		r.setAd(ad);
		r.setFreight(nf.format(zje).replaceAll(",",""));
		r.setRemarks(nf.format(wkp).replaceAll(",",""));
		r.setMax(ids);
		list.add(r);
		Gson g=new Gson();
		return g.toJson(list).toString();
	}


	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
		String[] idd=ids.split(",");
		List<Receivable> list =new ArrayList<Receivable>();
		for(String id:idd){
			list.add(receivableService.get(id));
		}

		Exportprofit e=new Exportprofit();
		e.exportreceivable(response,list);
	}
	/**
	 * 查看，增加，编辑应收表单页面
	 */
	@RequiresPermissions(value={"fee:receivable:view","fee:receivable:add","fee:receivable:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Receivable receivable, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			receivable.setProject(pro);
		}
		model.addAttribute("receivable", receivable);
		Cost c=new Cost();
		c.setRecive(receivable.getId());
		List<Cost>l=costService.findList(c);
		model.addAttribute("cost", l);
		return "modules/fee/receivableForm";
	}

	/**
	 * 保存应收
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:receivable:add","fee:receivable:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Receivable receivable, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, receivable)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		receivableService.save(receivable);//保存
		j.setSuccess(true);
		j.setMsg("保存应收成功");
		return j;
	}
	
	/**
	 * 删除应收
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivable:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Receivable receivable, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		receivableService.delete(receivable);
		j.setMsg("删除应收成功");
		return j;
	}


	/**
	 * 应收确认
	 * @param receivable
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public  String qr(Receivable receivable){
		receivable.setStatus("2");
		receivableService.save(receivable);

		return "";
	}

	/**
	 * 取消确认
	 * @param receivable
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "qxqr")
	public  String qxqr(Receivable receivable){
		receivable.setStatus("1");
		receivableService.save(receivable);

		return "";
	}
	/**
	 * 批量删除应收
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivable:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			receivableService.delete(receivableService.get(id));
		}
		j.setMsg("删除应收成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:receivable:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Receivable receivable, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Receivable> page = receivableService.findPage(new Page<Receivable>(request, response, -1), receivable);
    		new ExportExcel("应收", Receivable.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public Receivable detail(String id) {
		return receivableService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:receivable:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ImportReciveble> list = ei.getDataList(ImportReciveble.class);
			for (ImportReciveble receivable : list){
				try{
					Receivable r=receivableService.get(receivable.getPid());
					r.setProject(receivable.getProject());
					r.setFreight(receivable.getFreight());
					r.setReceived(receivable.getReceived());
					r.setShipmentNumbers(receivable.getShipmentNumbers());
					r.setThdh(receivable.getThdh());
					r.setStart(receivable.getStart());
					r.setArrive(receivable.getArrive());
					r.setWidth(receivable.getWidth());
					r.setPrice(receivable.getPrice());
					r.setWeight(receivable.getWeight());
					r.setCompany(receivable.getCompany());
					r.setSite(receivable.getSite());
					r.setMileage(receivable.getMileage());
					r.setSurplus(receivable.getSurplus());
					r.setSl(receivable.getSl());
					r.setHs(receivable.getHs());
					r.setQr(receivable.getQr());
					r.setAd(Double.parseDouble(receivable.getAd()));
					receivableService.save(r);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/receivable/list2/?repage";
    }
	
	/**
	 * 下载导入应收数据模板
	 */
	@RequiresPermissions("fee:receivable:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收数据导入模板.xlsx";
    		List<ImportReciveble> list = Lists.newArrayList();
    		new ExportExcel("应收数据", ImportReciveble.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/receivable/?repage";
    }
	

}